//
//  BeautyPictureVC.m
//  NewNest
//
//  Created by hesiyao on 16/1/15.
//  Copyright © 2016年 www.lanou3g.com蓝鸥科技. All rights reserved.
//

#import "BeautyPictureVC.h"
#import "BeautyPictureModal.h"
#import <AFHTTPSessionManager.h>
#import <AFNetworking.h>
#import "BeautyPictureCell.h"
#import <UIImageView+WebCache.h>
#import <MJRefresh.h>
@interface BeautyPictureVC () <UICollectionViewDataSource, UICollectionViewDelegate>
@property (nonatomic, retain) UICollectionView *collectionview;
@property (nonatomic, retain) NSMutableArray *dataArr;
@property (nonatomic, assign) NSInteger number;/**< 加载新数据时动态值 */
@end

@implementation BeautyPictureVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    // 数据处理
    [self dataHandler];
    // 创建视图
    [self createSubviews];
    // 动态值赋初值
    self.number = 2;
    //下拉刷新 上拉加载
    [self refresh];
    
}

/// 数据处理
- (void)dataHandler
{
    NSString *urlStr = @"http://appapi.17house.com/xiaoguotuApi.php?action=imageList&bid=6&page=1&pageSize=10&tagid=7";
    AFHTTPSessionManager *session = [AFHTTPSessionManager manager];
    [session GET:urlStr parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"成功");
        
        NSMutableArray *arr = responseObject[@"data"];
        self.dataArr = [BeautyPictureModal modelHanderWithArray:arr];
        [_collectionview reloadData];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"失败");
    }];
    // 结束下拉刷新
    [self.collectionview.mj_header endRefreshing];
}

/// 创建视图
- (void)createSubviews
{
    // 创建collectionView
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc] init];
    layout.itemSize = CGSizeMake((self.view.frame.size.width - 30) / 2, (self.view.frame.size.width - 30) / 2);
    layout.sectionInset = UIEdgeInsetsMake(10, 10, 0, 10);
    self.collectionview = [[UICollectionView alloc] initWithFrame:self.view.bounds collectionViewLayout:layout];
    self.collectionview.delegate = self;
    self.collectionview.dataSource = self;
    
    _collectionview.backgroundColor = [UIColor whiteColor];
    [_collectionview registerClass:[BeautyPictureCell class] forCellWithReuseIdentifier:@"cell"];
    [self.view addSubview:_collectionview];
    [_collectionview release];
}

/// 设置cell个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return _dataArr.count;
}

/// 设置cell
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    BeautyPictureCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cell" forIndexPath:indexPath];
//    cell.backgroundColor = [UIColor yellowColor];
    if (_dataArr.count != 0) {
        BeautyPictureModal *m = _dataArr[indexPath.row];
        [cell.imgview sd_setImageWithURL:[NSURL URLWithString:m.url]];
    }
    return cell;
}

/// 下拉刷新 上拉加载
- (void)refresh
{
    // 下拉刷新
    self.collectionview.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(dataHandler)];
    [self.collectionview.mj_header beginRefreshing];
    
    //上拉加载
    self.collectionview.mj_footer = [MJRefreshAutoFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadNewData)];
    //判断如果保存数据的数组不为空 就加载新的数据
    if (_dataArr.count != 0) {
        [self.collectionview.mj_footer beginRefreshing];
    }
}

/// 上拉加载方法
- (void)loadNewData
{
    NSString *urlStr = [NSString stringWithFormat:@"http://appapi.17house.com/xiaoguotuApi.php?action=imageList&bid=6&page=%ld&pageSize=10&tagid=7", self.number];
    [[AFHTTPSessionManager manager] GET:urlStr parameters:nil progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"美图加载成功");
        // 创建新的数组用来保存新数据
        NSArray *newDataArr = [NSArray array];
        newDataArr = [BeautyPictureModal modelHanderWithArray:responseObject[@"data"]];
        // 将新的数据依次加到数据驻足里面
        for (NSInteger i = 0; i < 10; i++) {
            [_dataArr addObject:newDataArr[i]];
        }
        // 刷新collectionView
        [self.collectionview reloadData];
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"美图加载失败");
    }];
    
    // 结束上拉加载
    [self.collectionview.mj_footer endRefreshing];
    // 动态值加一
    self.number += 1;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
